package com.tyylab.kestrel.framework.spring.web.impl;

import com.tyylab.kestrel.framework.util.HeaderPropagationConfig;
import com.tyylab.kestrel.framework.util.ContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;

/**
 * Web header interceptor for extracting context headers from HTTP requests
 * Reads tenant_id, request_id and other configured headers and sets them to thread local
 * 
 * @author tyylab
 */
@Slf4j
@Component
public class WebHeaderInterceptor implements HandlerInterceptor {
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // Clear previous context
        ContextUtil.clear();
        
        // Extract headers from request
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                
                // Check if this header should be propagated
                if (HeaderPropagationConfig.shouldPropagate(headerName)) {
                    String headerValue = request.getHeader(headerName);
                    if (headerValue != null && !headerValue.trim().isEmpty()) {
                        ContextUtil.set(headerName, headerValue);
                        log.debug("Extracted header from request: " + headerName + " = " + headerValue);
                    }
                }
            }
        }
        
        return true;
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // Clear context after request completion
        ContextUtil.clear();
        log.debug("Cleared context after request completion");
    }
} 